# -*- coding: utf-8 -*-
# @project: for_share
# @Time    : 2023/12/1 14:53
# @Author  : Dreamstar
# @File    : polar.py
# @Desc    : 用于编辑一个施密特图绘制的demo
#   1.在qtdesigner中添加 GraphicsView 作为图片绘制的容器
#   2.搜索 plot 关键词，查看所有相关的代码。


import sys
import numpy as np
import pandas as pd
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QFileDialog, QComboBox, \
    QGraphicsScene, QGraphicsProxyWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt


class RoseDiagramApp(QMainWindow):
    def __init__(self):
        super().__init__()

        # 从 UI 文件中加载界面
        self.load_ui()

        self.file_path = None  # 用于存储选择的文件路径

        # 初始化 Matplotlib 组件 - plot
        self.figure, self.ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
        self.canvas = FigureCanvas(self.figure)

        # 将 Matplotlib 组件嵌入到容器中 - plot
        # 在 QGraphicsView 中插入 FigureCanvas - plot
        self.proxy = QGraphicsProxyWidget()
        self.proxy.setWidget(self.canvas)
        self.graphics_scene = QGraphicsScene(self)
        self.graphics_view.setScene(self.graphics_scene)
        self.graphics_scene.addItem(self.proxy)

        # 为按钮绑定点击事件
        self.load_data_button.clicked.connect(self.load_data)
        self.plot_button.clicked.connect(self.plot_rose_diagram)

        self.show()

    def load_ui(self):
        # 从 Qt Designer 生成的 .ui 文件加载界面
        uic.loadUi('polar.ui', self)

        # 获取 UI 中的控件
        self.load_data_button = self.findChild(QtWidgets.QPushButton, 'loadDataButton')
        self.column_selector = self.findChild(QComboBox, 'columnSelector')
        self.plot_button = self.findChild(QtWidgets.QPushButton, 'plotButton')
        self.graphics_view = self.findChild(QtWidgets.QGraphicsView, 'graphicsView')  # plot

    def load_data(self):
        file_dialog = QFileDialog(self)  # 文件选择功能
        file_dialog.setNameFilter("Data Files (*.csv *.xlsx);;All Files (*)")

        if file_dialog.exec_():
            file_path = file_dialog.selectedFiles()[0]

            if file_path.lower().endswith('.csv'):
                data = pd.read_csv(file_path)
            elif file_path.lower().endswith(('.xlsx', '.xls')):
                data = pd.read_excel(file_path)
            else:
                print("Error: Unsupported file format.")
                return

            self.file_path = file_path  # 存储文件路径供后续使用
            self.populate_column_selector(data.columns)

    def populate_column_selector(self, columns):
        self.column_selector.clear()
        self.column_selector.addItems(columns)

    def plot_rose_diagram(self):
        selected_column = self.column_selector.currentText()
        if selected_column:
            if self.file_path.lower().endswith('.csv'):
                data = pd.read_csv(self.file_path)
            elif self.file_path.lower().endswith(('.xlsx', '.xls')):
                data = pd.read_excel(self.file_path)
            else:
                print("Error: Unsupported file format.")
                return
            self.update_rose_diagram(data[selected_column])

    def update_rose_diagram(self, data):
        self.ax.clear()
        self.create_rose_diagram()  # 重置施密特图

        # 绘制施密特图
        n, bins, patches = self.ax.hist(np.radians(data), bins=36, color='darkred', alpha=0.7)

        for patch in patches:
            patch.set_facecolor('red')

        self.ax.set_title(f"Rose Diagram - {self.column_selector.currentText()}")
        self.canvas.draw()

    def create_rose_diagram(self):
        # 设置极坐标图属性
        self.ax.set_theta_offset(np.pi / 2)
        self.ax.set_theta_direction(-1)
        self.ax.set_rlabel_position(90)
        self.ax.grid(True)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = RoseDiagramApp()
    sys.exit(app.exec_())

